<template>
  <div>
    <el-card class="card_box_commodity_information">
      <!--顶部返回框-->
      <el-page-header @back="goBack" :content="commodityInformation.text"
                      style="line-height: 20px;"></el-page-header>

      <el-row>

        <!--左卡片-->
        <el-col :span="10">
          <el-card class="left_card" shadow="hover">
            <div>
              <el-image
                  style="width: 100%; height: 380px; margin-top: 20px"
                  :src="handlerImg(commodityInformation.picture)"
                  fit="fill"></el-image>
            </div>
          </el-card>
        </el-col>

        <!--右卡片-->
        <el-col :span="14">
          <el-card class="right_card" shadow="hover">

            <h3>{{ commodityInformation.text }}</h3>
            <el-row>
              <el-col :span="5">
                <span style="font-size: 30px;color: #F56C6C;font-weight:bold">￥{{ commodityInformation.price }}</span>
              </el-col>
              <el-col :span="14" style="margin-top: 6px">
                <el-tag style="margin-left: 30px">{{ commodityInformation.type }}</el-tag>
              </el-col>
              <el-col :span="5" style="margin-top: 18px">
                <span style="margin-left: 240px ">历史销量&nbsp;&nbsp;&nbsp;{{ commodityInformation.historicalSaleCount }}
                </span>
              </el-col>
            </el-row>


            <el-divider></el-divider>

            <el-card shadow="never">
              <el-row style="margin-top: 5px">
                <el-col :span="6">
                  <span style="font-weight: bold;font-size: 18px">餐厅名称</span>
                </el-col>
                <el-col :span="6" style="margin: -2px">
                  <span style="color: #F56C6C;font-size: 23px">{{ this.restaurantName }}</span>
                </el-col>
              </el-row>

              <el-row style="margin-top: 5px">
                <el-col :span="6">
                  <span style="font-weight: bold;font-size: 18px">美食评价</span>
                </el-col>

                <el-col :span="8">
                  <el-rate
                      v-model="commodityInformation.appraiseScore"
                      disabled
                      show-score
                      text-color="#ff9900">
                  </el-rate>
                </el-col>

              </el-row>

              <el-row style="margin-top: 5px">
                <el-col :span="6">
                  <span style="font-weight: bold;font-size: 18px">库存</span>
                </el-col>
                <el-col :span="6">
                  <span>{{ commodityInformation.saleCount }}</span>
                </el-col>
              </el-row>

              <el-row style="margin-top: 5px">
                <el-col :span="6">
                  <span style="font-weight: bold;font-size: 18px">购买人数</span>
                </el-col>
                <el-col :span="6">
                  <span>{{ commodityInformation.peopleBuy }}</span>
                </el-col>
              </el-row>

            </el-card>

            <div v-if="user.identity===0">
              <el-row style="margin-left: 25px;margin-top: 15px">
                <el-col :span="3" style="padding: 5px">
                  <span style="font-size:16px">数量</span>
                </el-col>
                <el-col :span="6">
                  <el-input-number v-model="num" :min="1" :max="commodityInformation.saleCount" size="small"></el-input-number>
                </el-col>
              </el-row>

              <!--按钮-->

              <el-row style="margin-top: 20px">
                <el-col :span="5">
                  <el-button type="warning" @click="purchaseNow" :disabled="commodityInformation.saleCount===0">立即购买
                  </el-button>
                </el-col>

                <el-col :span="4">
                  <el-button type="danger" @click="addToShoppingCart">加入购物车</el-button>
                </el-col>
              </el-row>
            </div>

          </el-card>
        </el-col>
      </el-row>

      <br />

      <el-row>
        <el-col :span="20">
          <el-card body-style="padding:30px;" class="card_show_commodity_information">
            <vue-seamless-scroll :data="commodityComments" class="seamless-warp" :class-option="classOption">

              <div v-for="i in commodityComments" :key="i">
                <el-card class="card_content" shadow="hover">

                  <el-row>
                    <el-col :span="6">
                      <span style="font-weight: bolder;font-size: 25px">用&ensp;&ensp;户:</span>
                    </el-col>
                    <el-col :span="6">
                      <el-tag>{{i.userName}}</el-tag>
                    </el-col>
                  </el-row>

                  <el-row style="margin-top: 10px">
                    <el-col :span="6" >
                      <span style="font-weight: bolder;font-size: 20px">针对餐厅的服务评价:&ensp;</span>
                    </el-col>
                    <el-col :span="6" style="margin-top: 5px">
                      <el-rate
                          v-model="i.appraiseService"
                          disabled
                          show-score
                          text-color="#ff9900">
                      </el-rate>
                    </el-col>
                  </el-row>

                  <el-row style="margin-top: 10px">
                    <el-col :span="6">
                      <span style="font-weight: bolder;font-size: 20px">针对美食的评价:&ensp;</span>
                    </el-col>
                    <el-col :span="18">
                      <span style="font-size: 18px">{{i.appraiseInformation}}</span>
                    </el-col>
                  </el-row>


                </el-card>
              </div>
            </vue-seamless-scroll>

          </el-card>

        </el-col>
      </el-row>
    </el-card>

    <!--购买界面-->
    <el-dialog
        title="支付界面"
        :visible.sync="dialogVisiblePurchaseNow"
        width="40%"
    >

      <div style="">
        <h3>订单信息</h3>

        <el-card shadow="hover" style="padding: 0">
          <el-row>
            <el-col :span="4">
              <strong>美食名称</strong>
            </el-col>

            <el-col :span="20">
              <span>{{ commodityInformation.text }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>商品价格</strong>
            </el-col>

            <el-col :span="6">
              <span>￥{{ commodityInformation.price }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>购买数量</strong>
            </el-col>

            <el-col :span="6">
              <span>{{ num }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>用户积分</strong>
            </el-col>

            <el-col :span="6">
              <span>{{ user.integral }}</span>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <div style="margin-left: 20px;margin-top: 10px">
        <el-row>
          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black;">配送费</strong>
          </el-col>

          <el-col :span="6" style="margin-top: 5px">
            <strong style="font-size: 26px;color: #F56C6C">￥{{ delivery | numFilter}}</strong>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black">应付金额</strong>
          </el-col>

          <el-col :span="7" style="margin-top: 5px">
            <strong style="font-size: 26px;color: #F56C6C">￥{{ sum | numFilter}}</strong>
          </el-col>

          <el-col :span="5" style="margin-top: 13px">
            <strong style="color: black">实付金额</strong><br>
            <span style="font-weight: bold">(积分抵扣后)</span>
          </el-col>

          <el-col :span="9" style="margin-top: 0px">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ sumMinusIntegral | numFilter }}</strong>
          </el-col>

        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-popconfirm title="确定支付该订单吗？" @confirm="payTheOrder">
        <el-button type="primary" slot="reference">确定支付</el-button>
        </el-popconfirm>
        <el-button @click="handleClose" style="margin-left: 10px">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {getCommodityById} from "@/api/user/commodity/userCommodity";
import {getGeneralUserById} from "@/api/general/userGeneral";
import {comprehensivePurchaseCommodity} from "@/api/user/comprehensive/purchase";
import {addToCart, payMoney} from "@/api/user/cart/cart";
import {getUserInformation, setUserInformation} from "@/api/user";
import {selectInformationByCommodityId} from "@/api/merchant/commodity/comment";
import vueSeamlessScroll from 'vue-seamless-scroll'
import {getFee, getWeatherInformation} from "@/api/weather";

export default {
  name: "CommodityInformation",

  props:["commodityId","restaurantId","restaurantName"],

  components: {
    vueSeamlessScroll
  },

  data() {
    return {
      /**
       * 立即购买页面是否显示
       */
      dialogVisiblePurchaseNow: false,

      /**
       * 美食信息
       */
      commodityInformation: {},

      /**
       * 数量 (购买/加入购物车),默认为1
       */
      num: '1',

      /**
       * 支付总金额，默认为0
       */
      sum: '0',

      /**
       * 积分抵扣后支付总金额
       */
      sumMinusIntegral: '0',

      /**
       * 购买美食的用户
       */
      user: undefined,

      /**
       * 针对当前商品的评价内容
       */
      commodityComments:[],

      /**
       * 当前天气
       */
      weather:null,

      /**
       * 对应天气所需的配送费
       */
      delivery:'',
    }
  },

  // 监听属性 类似于data概念
  computed: {
    classOption() {
      return {
        step: 0.5, // 数值越大速度滚动越快
        limitMoveNum: 2, // 开始无缝滚动的数据量
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动)
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动)
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }
    }
  },

  created() {
    this.weather=getWeatherInformation();

    this.delivery=parseInt(getFee(this.weather));

    this.getGeneralUserById();
    this.getCommentList();
    this.getCommodityInformation();

  },
  filters: {

      numFilter (value) {
        // 截取当前数据到小数点后两位
        return parseFloat(value).toFixed(2)
      }

  },
  methods: {
    /**
     *返回餐厅首页
     */
    goBack() {
      this.$router.push({
        name:"restaurantInformation",
        params:{
          id:this.restaurantId,
          restaurantName:this.restaurantName
        }
      });
    },

    /**
     * 获取当前美食信息
     */
    getCommodityInformation() {

      const formData = new FormData();

      formData.append("id", this.commodityId);

      getCommodityById(formData).then(res => {
        this.commodityInformation = res.commodity;

      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })

    },

    /**
     * 立即支付按钮click事件,弹出支付界面
     */
    purchaseNow() {
      this.dialogVisiblePurchaseNow = true
      this.sum = this.num * this.commodityInformation.price+this.delivery;
      this.sumMinusIntegral = this.sum - Math.floor(this.user.integral / 100);
    },

    /**
     *  商品加入购物车
     */
    addToShoppingCart() {
      const formData = new FormData();

      formData.append("userId", this.user.id);
      formData.append("commodityId", this.commodityInformation.id);
      formData.append("num", this.num);
      formData.append("isShopping", '1');

      formData.append("delivery", '0');

      addToCart(formData).then(res=>{
        if(res.message===1){
          this.$message.success("加入成功");
        }
      }).catch(()=>{
        this.$message({
          message: "error",
          type: "error"
        })
      })

    },

    /**
     * 确定支付
     * 将对应天气相应的配送费传向后端
     */
    payTheOrder() {
      if (this.user.balance < this.sumMinusIntegral) {
        this.$message.warning("余额不足，无法进行支付");
      } else {
        let order = {
          userId: this.user.id,
          commodityId: this.commodityInformation.id,
          purchaseCount: this.num,
          delivery: this.delivery
        }

        comprehensivePurchaseCommodity(order).then(res => {
          if (res.information === 0) {
            this.$message.warning("该商品库存不足，无法进行支付");
          } else if (res.information === 1) {
            this.pay()
            this.num = '1';
            this.dialogVisiblePurchaseNow = false;
          }
        }).catch(() => {
          this.$message.error("购买失败，请重新购买");
        })
      }
    },

    /**
     * 支付
     */
    pay(){
      let user = {
        id: this.user.id,
        balance: this.sum
      }
      payMoney(user).then(res => {
        if(res.message === 1){
          this.getGeneralUserById()
          this.getCommodityInformation()
          this.$message.success("购买成功，请前往“购买记录”查看详细信息");
        }
      })
    },

    /**
     * 展示图片
     */
    handlerImg(picture){
      return "data:image/jpeg;base64," + picture;
    },

    /**
     * 获得评论列表
     */
    getCommentList() {
      const formData=new FormData();

      formData.append("commodityId", this.commodityId);

      selectInformationByCommodityId(formData).then(res=>{
        this.commodityComments=res.information;
      })

    },

    /**
     * 获得用户信息
     */
    getGeneralUserById() {
      const user = eval('(' + getUserInformation() + ')');

      const formData = new FormData();

      formData.append("id", user.id);


      getGeneralUserById(formData).then(res => {
        this.user = res.user;
        setUserInformation(this.user);

      }).catch(() => {
        this.$message.error("用户信息获取失败");
      })
    },

    /**
     * 关闭页面
     */
    handleClose() {
      this.num = '0';
      this.dialogVisiblePurchaseNow = false;
      this.$message.info("交易取消");
    },


  }
}
</script>

<style lang="less">
.card_box_commodity_information{
  height: 86vh;
}

.left_card {
  margin-top: 20px;
  height: 480px;
}

.right_card {
  height: 480px;
  margin-top: 20px;
  margin-right: 20px;
  margin-left: 10px;
}

//.el-divider--horizontal {
//  margin-top: 5px;
//  margin-bottom: 10px;
//  width: 100%;
//}

/* el-divider 修改高度&虚线效果 */
div[class="el-divider el-divider--horizontal"]{
  margin: 15px 0px 20px 0px;
  background-color: #DCDFE6;
  //border-top: 1px dashed #e8eaec;
}

.el-dialog__body {
  padding: 10px 10px;
}

.card_show_commodity_information {
  margin: 0 auto;
  width: 100vh;
  height: auto;
  text-align: center;
}

div .el-page-header__content{
  display: block;
  text-align: center;
  font-size: 35px;
  font-weight: bold;
  font-family: "楷体";
}


</style>
